package fhq.hcmute.edu.vn.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import fhq.hcmute.edu.vn.adapter.FileAdapter;
import fhq.hcmute.edu.vn.languages.Language;
import fhq.hcmute.edu.vn.message.MessageFactory;
import fhq.hcmute.edu.vn.message.MyMessage;
import fhq.hcmute.edu.vn.network.SendAndReceive;
import fhq.hcmute.edu.vn.system.MyFile;
import fhq.hcmute.edu.vn.system.MyFolder;
import fhq.hcmute.edu.vn.system.MySystem;
import fhq.hcmute.edu.vn.util.BundleUtil.Search;
import fhq.hcmute.edu.vn.util.HandlerRequestUtil;
import fhq.hcmute.edu.vn.util.ProjectUtil;

public class RemoteFileActivity extends Activity {
	private FileAdapter fileAdapter;
	private GridView gridView;
	private Button btnSearch;
	private Button btnBack;
	private Button btnHome;
	private List<MySystem> dataGridviewTemp;
	private boolean isDisplaySearchResult = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Language.updateLanguageSystem(getBaseContext());
		setContentView(R.layout.activity_remote_file);
		init();
	}

	private void init() {
		gridView = (GridView) findViewById(R.id.gridView);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnSearch = (Button) findViewById(R.id.btnSearch);
		btnHome = (Button) findViewById(R.id.btnHome);
		MyMessage message = MessageFactory.createPWDMessage();
		excuteCommand(message);
		gridView.setOnItemClickListener(onItemClick);
		gridView.setOnItemLongClickListener(onItemLongClickListener);
		btnSearch.setOnClickListener(onClickSearch);
		btnBack.setOnClickListener(onClickBack);
		btnHome.setOnClickListener(onClickHome);
		registerForContextMenu(gridView);
	}

	@Override
	protected void
			onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ProjectUtil.REQUEST_CODE_SEARCH_FILE) {
			if (resultCode == ProjectUtil.RESULT_CODE_SEARCH_FILE) {
				Bundle bundle = data.getExtras();
				String[] fileType = bundle.getStringArray(Search.FILE_TYPE);
				String keyword = bundle.getString(Search.KEY_WORD);
				String folderName = bundle.getString(Search.FOLDER_NAME);
				MyFolder path = (MyFolder) fileAdapter
						.getObjectByName(folderName);
				MyMessage message = MessageFactory.createSearchMessage(
						path, keyword, fileType);
				excuteCommand(message);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private OnClickListener onClickSearch = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			dataGridviewTemp =
					new ArrayList<MySystem>(fileAdapter.getObjects());
			Intent intent = new Intent(getApplicationContext(),
					SearchRemoteFileActivity.class);
			ArrayList<String> list = fileAdapter.getStrings();
			intent.putStringArrayListExtra(Search.LIST_PATH, list);
			startActivityForResult(intent, ProjectUtil.REQUEST_CODE_SEARCH_FILE);
			isDisplaySearchResult = true;
		}

	};
	private OnClickListener onClickBack = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (isDisplaySearchResult) {
				fileAdapter = new FileAdapter(RemoteFileActivity.this,
						dataGridviewTemp);
				gridView.setAdapter(fileAdapter);
				isDisplaySearchResult = false;
				dataGridviewTemp = null;
			} else {
				MyMessage message = MessageFactory.createTurnBackMessage();
				excuteCommand(message);
			}
		}
	};
	private OnClickListener onClickHome = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			MyMessage message = MessageFactory.createUpToRootMessage();
			excuteCommand(message);
		}
	};

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		getMenuInflater()
				.inflate(R.menu.context_menu_remote_file_activity, menu);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuItemOpen:
			MySystem system = (MySystem) gridView.getTag();
			if (system instanceof MyFile) {
				MyMessage message =
						MessageFactory.createExcuteFileMessage((MyFile) system);
				excuteCommand(message);
			}
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	private OnItemLongClickListener onItemLongClickListener =
			new AdapterView.OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					List<MySystem> systems = fileAdapter.getObjects();
					MySystem item = systems.get(arg2);
					gridView.setTag(item);
					return false;
				}
			};
	private OnItemClickListener onItemClick =
			new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View row,
						int position, long arg3) {
					List<MySystem> systems = fileAdapter.getObjects();
					MySystem item = systems.get(position);

					if (item instanceof MyFolder) {
						MyMessage message = MessageFactory
								.createChangeDirectoryMessage((MyFolder) item);
						excuteCommand(message);
					}
				}

			};

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == HandlerRequestUtil.REMOTE_FILE_REQUEST) {
				MyMessage message = (MyMessage) msg.obj;
				if (message != null) {
					if (message.getFrom() == MessageFactory.EXECUTE_FILE) {
						Boolean success = (Boolean) message.getFirstData();
						if (!success) {
							Toast.makeText(getApplicationContext(), "error",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						if (message.getFirstData() instanceof MyFolder) {
							MyFolder folder = (MyFolder) message.getFirstData();
							fileAdapter =
									new FileAdapter(RemoteFileActivity.this,
											folder.getFolders());
							gridView.setAdapter(fileAdapter);
						}
					}
				} else {
					Toast.makeText(getApplicationContext(), "Server is down",
							Toast.LENGTH_SHORT).show();
					finish();
				}
			}
			super.handleMessage(msg);
		}

	};

	private void excuteCommand(MyMessage message) {
		SendAndReceive fromServerTask =
				new SendAndReceive(RemoteFileActivity.this,
						HandlerRequestUtil.REMOTE_FILE_REQUEST, handler);
		fromServerTask.execute(message);
	}

	@Override
	public final boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuItemRefresh:
			MyMessage message = MessageFactory.createRefreshMessage();
			excuteCommand(message);
			break;
		case R.id.menuItemExit:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public final boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu_remote_file_activity, menu);
		return super.onCreateOptionsMenu(menu);
	}
}
